/*
 * LeadSearchScreen.java
 *
 * ?<your company here>, 2003-2008
 * Confidential and proprietary.
 */

package com.peakproducts;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import org.json.me.JSONObject;
import org.json.me.util.Utils;

import com.peakproducts.ConnectionThread;
import com.peakproducts.SearchResultScreen;

/**
 * 
 */
class LeadSearchScreen   extends PeakScreen{
    private BasicEditField leadNumber = new BasicEditField("Lead Number:  ", "");
    private BasicEditField customName = new BasicEditField("Customer Full Name:  ", "");
    private BasicEditField phoneNumber = new BasicEditField("Phone No.:  ", "");
    private PeakField searchBtn = new PeakField("Search");
    private PeakField logoutBtn = new PeakField("Logout");
	private HorizontalFieldManager hfm = new HorizontalFieldManager();
    private ConnectionThread connThread; 
    LeadSearchScreen(ConnectionThread connThread) {  
        this.connThread = connThread;
        FieldListener sendListener = new FieldListener();
        searchBtn.setChangeListener(sendListener);
        logoutBtn.setChangeListener(sendListener);
        setTitle("Lead Manager - Search Lead");
        add(leadNumber);
        add(customName);
        add(phoneNumber);
        add(new SeparatorField()); 
        hfm.add(searchBtn);
        hfm.add(logoutBtn);
        add(hfm);
    }
    
     public boolean onClose() {
        connThread.stop();
        close();
        return true;
    }
    
    private String getFieldData() {
    	StringBuffer sb = new StringBuffer();
    	sb.append("/userid/");
    	sb.append(Utils.contractor_id);
        sb.append("/leadId/");
        sb.append(leadNumber.getText().equals("")?"null":leadNumber.getText());
        sb.append("/customName/");
        sb.append(HURLEncoder.URLEncode(customName.getText().equals("")?"null":customName.getText()));
        sb.append("/phoneNo/");
        sb.append(HURLEncoder.URLEncode(phoneNumber.getText().equals("")?"null":phoneNumber.getText()));
        return sb.toString();
    }
    
    private void parseResults( String responseContent ){
    	try{
    		JSONObject resultObject = new JSONObject(responseContent);
    		String leadStatus = resultObject.getString("status");
    		if(leadStatus.equals("false")){
    			Status.show("Please enter lead number or custom name or phoneNo.");
    		}else if(leadStatus.equals("no_result")){
    			Status.show("There are no matched result.");
    		}else if(leadStatus.equals("true")){
    			SearchResultScreen searchResult = new SearchResultScreen(connThread, resultObject);
    			UiApplication.getUiApplication().pushScreen(searchResult);
    			close();
    		}else{
    			Status.show("Error when search leads, please try again.");
    		}
    	}catch(Exception e)
    	{
    		Status.show("Search result error, please contact system manager.");
    	}
    }
    
    class FieldListener implements FieldChangeListener {
        public void fieldChanged(Field field, int context) {
        	//Status.show(((PeakField)field).getLabel());
        	if(!((PeakField)field).getLabel().equals("Logout"))
        	{
	            StringBuffer sb = new StringBuffer("Searching...");
	            connThread.get(Utils.restURL+"/Lead/Search" + getFieldData());
	            while (connThread.sending) {
	                try {
	                    Status.show( sb.append(".").toString() );
	                    Thread.sleep(100);
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	            }
	
	            if (connThread.sendResult) {
	                Status.show("Transmission Successful");
	                parseResults( connThread.responseContent );
	            } else {
	                Status.show("Transmission Failed");
	            }
        	}else{
        		Utils.contractor_id="";
        		UiApplication.getUiApplication().pushScreen(new LoginScreen(connThread));
        		close();
        	}
        }
    }
} 
